package cn.kvchoi.reactor_nio.server.handlers;

import cn.kvchoi.reactor_nio.server.EventHandler;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

public class ReadEventHandler implements EventHandler
{

    @Override
    public void handleEvent(SelectionKey key)
    {  
        System.out.println(Thread.currentThread().getName() + ": Read event handler");

        try {
            SocketChannel socketChannel = (SocketChannel) key.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int readLength = socketChannel.read(byteBuffer);
            while (readLength > 0) {
                System.out.println(new String(byteBuffer.array(), 0, readLength));
                readLength = socketChannel.read(byteBuffer);
            }
            //对socketChannel注册写的事件
            socketChannel.register(key.selector(), SelectionKey.OP_WRITE);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("=============");
    }
  
} 